<template>
  <div class="mod-config">
    <el-row :gutter="20">

      <el-col :span="24">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
          <el-form-item label="设备名称">
            <el-input v-model="dataForm.deviceName" placeholder="设备名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="设备id">
            <el-input v-model="dataForm.deviceId" placeholder="设备id" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-select
              v-model="selectUser"
              filterable
              remote
              clearable
              @change="userChange"
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="searchUserByName"
              :loading="searchUserLoading">
              <el-option
                v-for="item in userPage.userDataList"
                :key="item.userId"
                :label="item.username"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="地区">
            <el-input v-model="dataForm.address" placeholder="地区" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
            <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
            <el-button type="danger" @click="deleteHandle()"
                       :disabled="dataListSelections.length <= 0">批量删除
            </el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="name"
            header-align="center"
            align="center"
            label="设备名称">
          </el-table-column>
          <el-table-column
            prop="lotDeviceId"
            header-align="center"
            align="center"
            label="设备id">
          </el-table-column>
          <el-table-column
            prop="userName"
            header-align="center"
            align="center"
            label="用户名">
          </el-table-column>
          <el-table-column
            prop="simCode"
            header-align="center"
            align="center"
            label="sim卡号">
          </el-table-column>
          <el-table-column
            prop="online"
            header-align="center"
            align="center"
            label="设备状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.online">在线</el-tag>
              <el-tag type="danger" v-if="scope.row.online==false">离线</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="deviceKind"
            header-align="center"
            align="center"
            label="设备类型">
          </el-table-column>

          <el-table-column
            header-align="center"
            align="center"
            label="地区">
            <template slot-scope="scope">
              {{ scope.row.province + scope.row.city + scope.row.area }}
            </template>
          </el-table-column>

          <el-table-column
            prop="longitude"
            header-align="center"
            align="center"
            label="经度">
          </el-table-column>
          <el-table-column
            prop="latitude"
            header-align="center"
            align="center"
            label="维度">
          </el-table-column>
          <el-table-column
            prop="createTime"
            header-align="center"
            align="center"
            label="创建时间">
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
              <!--              <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>-->
              <el-button type="text" size="small" @click="showDeviceChartClick(scope.row)">查看数据</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <el-dialog
      :visible.sync="deviceDataChartVisible"
      title="设备数据"
      width="60%"
      center
    >
      <el-date-picker
        v-model="historyDay"
        type="date"
        :editable=false
        @change="historyDayChange"
        :picker-options="historyDayPickerOptions"
        style="margin-left: 75%"
        placeholder="选择日期">
      </el-date-picker>
      <div id="deviceChart" :style="{ height: '350px',width:'100%'}"></div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="deviceDataChartVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './device-add-or-update'

export default {
  data () {
    return {
      dataForm: {
        deviceId: '',
        deviceName: '',
        address: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      userPage: {
        dataListLoading: false,
        userDataList: [],
        limit: 10,
        page: 1,
        total: 0
      },
      userForm: {
        mobile: '',
        username: ''
      },
      selectUserId: 0,
      selectUser: '',
      selectDeviceId: 0,
      selectDevice: {},
      deviceDataChartVisible: false,
      searchUserLoading: false,
      historyDay: '',
      startDate: 0,
      endDate: 0,
      historyDayPickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      }
    }
  },
  components: {
    AddOrUpdate
  },
  activated () {
    this.getDataList()
    // this.getAppUserList()
  },
  mounted () {
    this.startDate = new Date(new Date(new Date().getTime() - 24 * 60 * 60 * 1000).setHours(0, 0, 0, 0)).getTime()
    this.endDate = new Date(new Date(new Date().getTime() - 24 * 60 * 60 * 1000).setHours(23, 59, 59, 999)).getTime()
    // this.showDeviceChart('0863409056158065')
  },
  methods: {
    historyDayChange (val) {
      let dayNow = new Date()
      if (val.getTime() > dayNow.getTime()) {
        this.$message.error('选择日期不能大于当前日期')
        return false
      }
      if (val != null) {
        console.info(val.getTime())
        this.startDate = val.getTime()
        this.endDate = val.getTime() + 24 * 60 * 60 * 1000 - 1
      } else {
        this.startDate = new Date(new Date(new Date().getTime() - 24 * 60 * 60 * 1000).setHours(0, 0, 0, 0)).getTime()
        this.endDate = new Date(new Date(new Date().getTime() - 24 * 60 * 60 * 1000).setHours(23, 59, 59, 999)).getTime()
      }
      console.info(this.startDate)
      console.info(this.endDate)
      this.showDeviceChart(this.selectDeviceId)
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/device/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'lotDeviceId': this.dataForm.deviceId,
          'userId': this.selectUserId,
          'deviceName': this.dataForm.deviceName,
          'address': this.dataForm.address
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    userRowClick (row) {
      this.selectUserId = row.userId
      this.getDataList()
    },
    searchUserByName (query) {
      if (query !== '') {
        this.loading = true
        this.userForm.username = query
        this.getAppUserList()
      } else {
        this.userPage.userDataList = []
      }
    },
    userChange (user) {
      console.info(user)
      this.selectUserId = user
    },
    getAppUserList () {
      this.$http({
        url: this.$http.adornUrl('/user/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'username': this.userForm.username
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.userPage.userDataList = data.page.list
          this.userPage.total = data.page.totalCount
        } else {
          this.userPage.userDataList = []
          this.userPage.total = 0
        }
      })
    },
    showDeviceChartClick (device) {
      this.selectDevice = device
      this.showDeviceChart(device.lotDeviceId)
    },
    showDeviceChart (deviceId) {
      this.deviceDataChartVisible = true
      this.selectDeviceId = deviceId
      console.info(deviceId)
      this.$http({
        url: this.$http.adornUrl('/deviceData/chartData'),
        method: 'get',
        params: this.$http.adornParams({
          'deviceId': this.selectDeviceId,
          'startDate': this.startDate,
          'endDate': this.endDate,
          'id': this.selectDevice.id
        })
      }).then(({data}) => {
        console.info(data)
        data = data.data
        if (data.hasOwnProperty('tempData')) {
          let tempData = data.tempData
          let tempSecondData = data.tempDataSecond
          let humiData = data.humiData
          let humiSecondData = data.humiSecondData
          let xDataList = data.xDataList
          let lineDataName = data.lineNameData
          let deviceChart = this.$echarts.init(document.getElementById('deviceChart'))
          deviceChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            title: {
              text: this.selectDevice.name + '-数据折线图'
            },
            legend: {
              data: lineDataName
            },
            xAxis: {
              type: 'category',
              data: xDataList
            },
            yAxis: {
              type: 'value'
            },
            series: [{
              name: lineDataName[0],
              data: tempData,
              type: 'line',
              smooth: true
            }, {
              name: lineDataName[1],
              data: humiData,
              type: 'line',
              smooth: true
            }, {
              name: lineDataName[2],
              data: tempSecondData,
              type: 'line',
              smooth: true
            }, {
              name: lineDataName[3],
              data: humiSecondData,
              type: 'line',
              smooth: true
            }]
          })
        }
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    userCurrentChangeHandle (val) {
      this.userPage.page = val
      this.getAppUserList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/device/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
  }
}
</script>
